package a2023.a1016;

import java.util.Arrays;

/**
 * @author lenovo
 * @date 2023/10/16
 */
public class a {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(singleNumber2(
                new int[]{0,1,2,2})));
    }

    public static int[] singleNumber(int[] nums) {
        Arrays.sort(nums);
        int right = nums.length - 1;
        if (right == 1) return nums;
        int left = 0;
        int num = 0;
        int[] ints = new int[2];
        while (left <= right) {
            if (nums[left] == nums[left + 1]) {
                left += 2;
            } else {
                ints[num] = nums[left];
                num++;
                left++;
            }
            if (num == 2) return ints;
            if (nums[right] == nums[right - 1]) {
                right -= 2;
            } else {
                ints[num] = nums[right];
                num++;
                right--;
            }
            if (num == 2) return ints;
        }
        return ints;
    }

    public static int[] singleNumber2(int[] nums) {
        int xorsum = 0;
        for (int num : nums) {
            xorsum ^= num;
        }
        // 防止溢出
        int lsb = (xorsum == Integer.MIN_VALUE ? xorsum : xorsum & (-xorsum));
        int type1 = 0, type2 = 0;
        for (int num : nums) {
            if ((num & lsb) != 0) {
                type1 ^= num;
            } else {
                type2 ^= num;
            }
        }
        return new int[]{type1, type2};
    }

}
